package com.hzxgs.tracelogstarter.trace;

import com.hzxgs.tracelogstarter.properties.TraceProperties;
import com.hzxgs.tracelogstarter.util.TraceUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ConditionalOnClass(value = {RequestInterceptor.class})
@Slf4j
public class FeignTraceInterceptor implements RequestInterceptor {

    @Resource
    private TraceProperties traceProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            if (traceProperties.getEnable()) {
                String traceId = TraceUtils.getTraceId();
                if (!StringUtils.isBlank(traceId)) {
                    requestTemplate.header(TraceUtils.TRACE_ID_HEADER, traceId);
                    requestTemplate.header(TraceUtils.SPAN_ID_HEADER, TraceUtils.getNextSpanId());
                }
            }
        } catch (Exception e) {
            log.error("feign透传traceId失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
